<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


  
  
  <link rel="stylesheet" href="/xieyuanhui/lib/needsharebutton/needsharebutton.css">

















  
  
  <link rel="stylesheet" href="/xieyuanhui/lib/fancybox/source/jquery.fancybox.css">







<link rel="stylesheet" href="/xieyuanhui/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/xieyuanhui/css/main.css?v=7.1.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/xieyuanhui/images/apple-touch-icon-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/xieyuanhui/images/favicon-32x32-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/xieyuanhui/images/favicon-16x16-next.png?v=7.1.0">


  <link rel="mask-icon" href="/xieyuanhui/images/logo.svg?v=7.1.0" color="#222">


  <link rel="manifest" href="/xieyuanhui/images/manifest.json">


  <meta name="msapplication-config" content="/xieyuanhui/images/browserconfig.xml">





<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/xieyuanhui/',
    scheme: 'Pisces',
    version: '7.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="zookeeper简介 中间件，提供协调服务 作用于分布式系统，发挥其优势，可以为大数据服务 至此Java，提供Java和C语言的客户端api  分布式系统 很多台计算机组成一个整体，一个整体一致对外并且处理同一请求 内部的每台计算机都可以相互通信（rest / rpc） 客户端到服务端的一次请求到相应结束会经历多台计算机   zookeeper的特性 一致性：数据一致性，数据按照顺序分批入库 原">
<meta name="keywords" content="中间件,zookeeper">
<meta property="og:type" content="article">
<meta property="og:title" content="zookeeper简介">
<meta property="og:url" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/16/zookeeper简介/index.html">
<meta property="og:site_name" content="xieyuanhui的笔记">
<meta property="og:description" content="zookeeper简介 中间件，提供协调服务 作用于分布式系统，发挥其优势，可以为大数据服务 至此Java，提供Java和C语言的客户端api  分布式系统 很多台计算机组成一个整体，一个整体一致对外并且处理同一请求 内部的每台计算机都可以相互通信（rest / rpc） 客户端到服务端的一次请求到相应结束会经历多台计算机   zookeeper的特性 一致性：数据一致性，数据按照顺序分批入库 原">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/16/zookeeper简介/img1.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/16/zookeeper简介/img2.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/16/zookeeper简介/img3.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/16/zookeeper简介/img4.jpg">
<meta property="og:updated_time" content="2019-07-25T13:35:03.836Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="zookeeper简介">
<meta name="twitter:description" content="zookeeper简介 中间件，提供协调服务 作用于分布式系统，发挥其优势，可以为大数据服务 至此Java，提供Java和C语言的客户端api  分布式系统 很多台计算机组成一个整体，一个整体一致对外并且处理同一请求 内部的每台计算机都可以相互通信（rest / rpc） 客户端到服务端的一次请求到相应结束会经历多台计算机   zookeeper的特性 一致性：数据一致性，数据按照顺序分批入库 原">
<meta name="twitter:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/16/zookeeper简介/img1.jpg">



  <link rel="alternate" href="/xieyuanhui/atom.xml" title="xieyuanhui的笔记" type="application/atom+xml">



  
  
  <link rel="canonical" href="http://xyh5513.gitee.io/xieyuanhui/2019/07/16/zookeeper简介/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>zookeeper简介 | xieyuanhui的笔记</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/xieyuanhui/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xieyuanhui的笔记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/xieyuanhui/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/xieyuanhui/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/xieyuanhui/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/xieyuanhui/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/xieyuanhui/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xyh5513.gitee.io/xieyuanhui/xieyuanhui/2019/07/16/zookeeper简介/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xieyuanhui">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/xieyuanhui/images/deer.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xieyuanhui的笔记">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">zookeeper简介

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-07-16 16:30:31" itemprop="dateCreated datePublished" datetime="2019-07-16T16:30:31+08:00">2019-07-16</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-07-25 21:35:03" itemprop="dateModified" datetime="2019-07-25T21:35:03+08:00">2019-07-25</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/xieyuanhui/categories/中间件/" itemprop="url" rel="index"><span itemprop="name">中间件</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          
            <span id="/xieyuanhui/2019/07/16/zookeeper简介/" class="leancloud_visitors" data-flag-title="zookeeper简介">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">3.8k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">3 分钟</span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="zookeeper简介"><a href="#zookeeper简介" class="headerlink" title="zookeeper简介"></a>zookeeper简介</h3><ul>
<li>中间件，提供协调服务</li>
<li>作用于分布式系统，发挥其优势，可以为大数据服务</li>
<li>至此Java，提供Java和C语言的客户端api</li>
</ul>
<h3 id="分布式系统"><a href="#分布式系统" class="headerlink" title="分布式系统"></a>分布式系统</h3><ul>
<li>很多台计算机组成一个整体，一个整体一致对外并且处理同一请求</li>
<li>内部的每台计算机都可以相互通信（rest / rpc）</li>
<li>客户端到服务端的一次请求到相应结束会经历多台计算机</li>
</ul>
<p><img src="/xieyuanhui/2019/07/16/zookeeper简介/img1.jpg" alt></p>
<h3 id="zookeeper的特性"><a href="#zookeeper的特性" class="headerlink" title="zookeeper的特性"></a>zookeeper的特性</h3><ul>
<li>一致性：数据一致性，数据按照顺序分批入库</li>
<li>原子性：事务要么成功要么失败，不会局部化</li>
<li>单一视图：客户端连接集群中的任一zookeeper节点，数据都是一致的</li>
<li>可靠性：每次对zookeeper的操作状态都会保存在服务端</li>
<li>实时性：客户端可以读取到zookeeper服务端的最新数据</li>
</ul>
<h3 id="Zookeeper主要目录介绍"><a href="#Zookeeper主要目录介绍" class="headerlink" title="Zookeeper主要目录介绍"></a>Zookeeper主要目录介绍</h3><ul>
<li>bin ： 主要的一些运行命令</li>
<li>conf：存放配置文件，其中我们需要修改zk.cfg</li>
<li>contrib：附加的一些功能</li>
<li>dist-maven：mvn编译后的目录</li>
<li>docs：文档</li>
<li>lib：需要依赖的 jar 包</li>
<li>recipes：案例 demo 代码</li>
<li>src：源码</li>
</ul>
<h3 id="zoo-cfg-配置"><a href="#zoo-cfg-配置" class="headerlink" title="zoo.cfg 配置"></a>zoo.cfg 配置</h3><ul>
<li>tickTime：用于计算的时间单元，比如 session 超时：N * tickTime</li>
<li>initLimit：用于集群，允许从节点连接并同步到 master 节点的初始化连接时间，以 tickTime 的倍数表示</li>
<li>syncLimit：用于集群，master 主节点与从节点之间发送消息，请求和应答时间长度（心跳机制）</li>
<li>dataDir：必须配置</li>
<li>dataLogDir：日志目录，如果不配置的话会和 dataDir 共用一个目录</li>
<li>clientPort：默认端口</li>
</ul>
<h3 id="Zookeeper基本数据模型"><a href="#Zookeeper基本数据模型" class="headerlink" title="Zookeeper基本数据模型"></a>Zookeeper基本数据模型</h3><ul>
<li>是一个树形结构，类似于前端开发中的 tree.js 插件</li>
</ul>
<p><img src="/xieyuanhui/2019/07/16/zookeeper简介/img2.jpg" alt></p>
<p><img src="/xieyuanhui/2019/07/16/zookeeper简介/img3.jpg" alt></p>
<ul>
<li>zk 的数据模型也可以理解为 linux /unix 的文件目录：/usr/local/…</li>
<li>每一个节点都称之为 znode，它可以有子节点，也可以有数据</li>
<li>每个节点分为临时节点和永久节点，临时节点在客户端断开后消失</li>
<li>每个 zk 节点都有自己的版本号，可以通过命令行来显示节点信息</li>
<li>每当节点数据发生变化，那么该节点的版本号会累加（乐观锁）</li>
<li>删除/修改过时节点，版本号不匹配则会报错</li>
<li>每个 zk 节点存储的数据不宜过大， 几 K 即可</li>
<li>节点可以设置权限 acl，可以通过权限来限制用户的访问</li>
</ul>
<h3 id="数据模型的基本操作"><a href="#数据模型的基本操作" class="headerlink" title="数据模型的基本操作"></a>数据模型的基本操作</h3><ul>
<li>客户端连接</li>
<li>查看 znode 结构</li>
<li>关闭客户端连接</li>
</ul>
<h3 id="Zookeeper-的作用体现"><a href="#Zookeeper-的作用体现" class="headerlink" title="Zookeeper 的作用体现"></a>Zookeeper 的作用体现</h3><ul>
<li>master 节点选举，主节点关了以后，从节点就会接手工作，并且保证这个节点是唯一的，这也是所谓的首脑模式，从而保证我们的集群是高可用的。</li>
<li>统一配置文件管理，即只需要部署一台服务器，则可以把相同的配置文件同步更新到其他所有服务器，此操作在云计算中用的特别多（假设修改了 redis 统一配置）</li>
<li>发布与订阅，类似消息队列 MQ（amq，rmq…），dubbo 发布者把数据存在 znode 上，订阅者则会读取这个数据</li>
<li>提供分布式锁，分布式环境中不同进程之间争夺资源，类似于多线程中的锁</li>
<li>集群管理，集群中保证数据的强一致性</li>
</ul>
<h3 id="Zookeeper-常用命令行操作"><a href="#Zookeeper-常用命令行操作" class="headerlink" title="Zookeeper 常用命令行操作"></a>Zookeeper 常用命令行操作</h3><p>./zkCli.sh : 进入 Zookeeper客户端进行命令后台</p>
<p>ls ：查看某一路径下的列表</p>
<p>ls2 ： 查看某一路径下的列表及状态</p>
<p>stat ： 查看某一路径下的状态</p>
<p>get ：获取某一路径下的数据及状态</p>
<h4 id="状态信息"><a href="#状态信息" class="headerlink" title="状态信息"></a>状态信息</h4><p>cZxid：节点 id</p>
<p>ctime：创建时间</p>
<p>mZxid：修改后的节点 id</p>
<p>mtime：修改时间</p>
<p>pZxid：子节点 id</p>
<p>numChildren：子节点数量</p>
<p>ephemeralOwner：0x0 表示永久节点，0x…..表示临时节点</p>
<p>dataVersion：数据版本号</p>
<h3 id="Session-的基本原理"><a href="#Session-的基本原理" class="headerlink" title="Session 的基本原理"></a>Session 的基本原理</h3><ul>
<li>客户端与服务端之间的连接存在会话</li>
<li>每个会话都可以设置一个超时时间</li>
<li>心跳结束，则 Session 过期</li>
<li>Session 过期，则临时节点 znode会被抛弃</li>
<li>心跳机制：客户端向服务端的 ping 包请求</li>
</ul>
<p>create：创建节点（-s 顺序节点，-e 临时节点）</p>
<p>set：修改某一个节点的值</p>
<p>delete：删除节点</p>
<h3 id="watcher-机制"><a href="#watcher-机制" class="headerlink" title="watcher 机制"></a>watcher 机制</h3><ul>
<li>针对每一个节点的操作，都会有一个监督者 -&gt; watcher</li>
<li>当监控的某个对象（znode）发生了变化，则触发 watcher 事件</li>
<li>zk 中 watcher 是一次性的，触发后立即销毁</li>
<li>父节点，子节点增删改都可以触发其 watcher</li>
<li>针对不同类型的操作，触发的 watcher 事件也不同：<ul>
<li>（子）节点创建事件</li>
<li>（子）节点删除事件</li>
<li>（子）节点数据变化事件</li>
</ul>
</li>
</ul>
<h3 id="Watcher-命令行"><a href="#Watcher-命令行" class="headerlink" title="Watcher 命令行"></a>Watcher 命令行</h3><ul>
<li>通过 get path [watch]</li>
<li>创建父节点触发：NodeCreated</li>
<li>修改父节点数据触发：NodeDataChanged</li>
<li>删除父节点触发：NodeDeleted</li>
</ul>
<h3 id="Watch-事件类型"><a href="#Watch-事件类型" class="headerlink" title="Watch 事件类型"></a>Watch 事件类型</h3><ul>
<li>ls 为父节点设置 watcher，创建子节点触发：NodeChildrenChanged</li>
<li>ls 为父节点设置 watcher，删除子节点触发：NodeChildrenChanged</li>
<li>ls 为父节点设置 watcher，修改子节点不触发（如果想要触发的话就要把子节点当作父节点来处理，使用 get 命令）</li>
</ul>
<h3 id="watcher-使用场景"><a href="#watcher-使用场景" class="headerlink" title="watcher 使用场景"></a>watcher 使用场景</h3><ul>
<li>统一资源配置</li>
</ul>
<p><img src="/xieyuanhui/2019/07/16/zookeeper简介/img4.jpg" alt></p>
<h3 id="ACL（Access-Control-Lists）权限控制"><a href="#ACL（Access-Control-Lists）权限控制" class="headerlink" title="ACL（Access Control Lists）权限控制"></a>ACL（Access Control Lists）权限控制</h3><ul>
<li>针对节点可以设置相关读写等权限，目的是为了保障数据安全性</li>
<li>权限 permissions 可以指定不同的权限范围以及角色</li>
</ul>
<h3 id="ACL-命令行"><a href="#ACL-命令行" class="headerlink" title="ACL 命令行"></a>ACL 命令行</h3><p>getAcl：获取某个节点的 acl 权限信息</p>
<p>setAcl：设置某个节点的 acl 权限信息</p>
<p>addauth：输入认证授权信息，注册时输入明文密码（登录），但是在 zk 的系统里，密码是以加密的形式存在的</p>
<h3 id="ACL-的构成"><a href="#ACL-的构成" class="headerlink" title="ACL 的构成"></a>ACL 的构成</h3><ul>
<li><p>zk 的 acl 通过 [schema​ : id :permissions]来构成权限列表</p>
<p>schema：代表采用的某种权限机制</p>
<p>id：代表允许访问的用户</p>
<p>permissions：权限组合字符串 </p>
</li>
<li><p>world : world 下只有一个 id，即只有一个用户，也就是 anyone，那么组合的写法是 world:anyone:[permissions]</p>
</li>
<li>auth：代表认证登录，需要注册用户有权限就可以，形式为 auth:user:password:[permissions]</li>
<li>digest：需要对密码加密才能访问，组合形式为 digest:username:BASE64(SHA1(password)):[permissions]</li>
<li>简而言之，auth 和 digest 的区别就是前者明文，后者密文。setAcl /path auth:lee:lee:cdrwa 与 setAcl /path digest:lee:BASE64(SHA1(password)) cdrwa 是等价的，在通过 addauth digest lee:lee 后都能操作指定节点的权限</li>
<li>ip：当设置 ip 为指定的 ip 地址，此时限制 ip 进行服务，比如 ip:192.168.1.1:[permissions]</li>
<li>super：代表超级管理员，拥有所有的权限</li>
</ul>
<p>权限字符串缩写 crdwa：</p>
<ul>
<li>CREATE：创建子节点</li>
<li>READ：获取节点/子节点</li>
<li>DELETE：删除子节点</li>
<li>WRITE：设置节点数据</li>
<li>ADMIN：设置权限</li>
</ul>
<h3 id="ACL-的常用使用场景"><a href="#ACL-的常用使用场景" class="headerlink" title="ACL 的常用使用场景"></a>ACL 的常用使用场景</h3><ul>
<li>开发/测试环境分离，开发者无权操作测试库的节点，只能看</li>
<li>生产环境上控制指定 ip 的服务可以访问相关节点，防止混乱</li>
</ul>
<h3 id="ACL-命令行学习"><a href="#ACL-命令行学习" class="headerlink" title="ACL 命令行学习"></a>ACL 命令行学习</h3><ul>
<li><p>world:anyone:cdrwa</p>
</li>
<li><p>auth:user:pwd:cdrwa</p>
<p>digest:user:BASE64(SHA1(pwd)):cdrwa</p>
<p>addauth digest user:pwd</p>
</li>
<li><p>super：</p>
<ul>
<li>修改 zkServer.sh 增加 super 管理员</li>
<li>重启 zkServer.sh</li>
</ul>
</li>
</ul>
<h3 id="zk-四字命令"><a href="#zk-四字命令" class="headerlink" title="zk 四字命令"></a>zk 四字命令</h3><ul>
<li>zk 可以通过它自身提供的简写命令来和服务器进行交互</li>
<li>需要使用到 nc 命令，安装：yum install nc</li>
<li><p>echo [command]| nc [ip] [port]</p>
</li>
<li><p>[stat] 查看 zk 的状态信息，以及是否 mode</p>
</li>
<li>[ruok] 查看当前 zkserver 是否启动，返回 imok</li>
<li>[dump] 列出未经处理的会话和临时节点</li>
<li>[conf] 查看服务器配置</li>
<li>[cons] 展示连接到服务器的客户端信息</li>
<li>[envi] 环境变量</li>
<li>[mntr] 监控信息</li>
<li>[wchs] 展示 watch 信息</li>
<li>[wchc] 与 [wchp]  session 与 watch 及 path 与 watch 信息</li>
</ul>
<h3 id="Zookeeper-集群搭建"><a href="#Zookeeper-集群搭建" class="headerlink" title="Zookeeper 集群搭建"></a>Zookeeper 集群搭建</h3><ul>
<li>zk 集群，主从节点，心跳机制（选举模式）</li>
<li>配置数据文件 myid 1/2/3 对应 server.1/2/3</li>
<li>通过 ./zkCli.sh -server [ip]:[port]检测集群是否配置成功</li>
</ul>

      
    </div>

    

    
    
    

    
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script type="text/javascript" src="http://jslibs.wuxubj.cn/sweetalert_mini/jquery-1.7.1.min.js"></script>
  <script src="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.mini.css">
 
  <p><span>本文标题:</span>zookeeper简介</p>
  <p><span>文章作者:</span>xieyuanhui</p>
  <p><span>发布时间:</span>2019年07月16日 - 16:30:31</p>
  <p><span>最后更新:</span>2019年07月25日 - 21:35:03</p>
  <p><span>原始链接:</span><a href="/xieyuanhui/2019/07/16/zookeeper简介/" title="zookeeper简介">http://xyh5513.gitee.io/xieyuanhui/2019/07/16/zookeeper简介/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://xyh5513.gitee.io/xieyuanhui/2019/07/16/zookeeper简介/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">CC BY-NC-SA 4.0</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    clipboard.on('success', $(function(){
      $(".fa-clipboard").click(function(){
        swal({   
          title: "",   
          text: '复制成功',   
          html: false,
          timer: 500,   
          showConfirmButton: false
        });
      });
    }));  
</script>

    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>您的支持将鼓励我继续创作</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/xieyuanhui/images/wechatpay.png" alt="xieyuanhui 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/xieyuanhui/images/alipay.jpg" alt="xieyuanhui 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/xieyuanhui/tags/中间件/" rel="tag"># 中间件</a>
          
            <a href="/xieyuanhui/tags/zookeeper/" rel="tag"># zookeeper</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
            
              <div id="needsharebutton-postbottom">
                <span class="btn">
                  <i class="fa fa-share-alt" aria-hidden="true"></i>
                </span>
              </div>
            
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/xieyuanhui/2019/07/12/Java并发编程和高并发解决方案（四）/" rel="next" title="Java并发编程和高并发解决方案（四）">
                <i class="fa fa-chevron-left"></i> Java并发编程和高并发解决方案（四）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/xieyuanhui/2019/07/20/理解epoll本质/" rel="prev" title="理解epoll本质">
                理解epoll本质 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/xieyuanhui/images/deer.png" alt="xieyuanhui">
            
              <p class="site-author-name" itemprop="name">xieyuanhui</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/xieyuanhui/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/xieyuanhui/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/xieyuanhui/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">114</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/xieyuanhui/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="/xieyuanhui/yuanhxie@163.com" title="E-Mail &rarr; yuanhxie@163.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#zookeeper简介"><span class="nav-text">zookeeper简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分布式系统"><span class="nav-text">分布式系统</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#zookeeper的特性"><span class="nav-text">zookeeper的特性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Zookeeper主要目录介绍"><span class="nav-text">Zookeeper主要目录介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#zoo-cfg-配置"><span class="nav-text">zoo.cfg 配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Zookeeper基本数据模型"><span class="nav-text">Zookeeper基本数据模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据模型的基本操作"><span class="nav-text">数据模型的基本操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Zookeeper-的作用体现"><span class="nav-text">Zookeeper 的作用体现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Zookeeper-常用命令行操作"><span class="nav-text">Zookeeper 常用命令行操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#状态信息"><span class="nav-text">状态信息</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Session-的基本原理"><span class="nav-text">Session 的基本原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#watcher-机制"><span class="nav-text">watcher 机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Watcher-命令行"><span class="nav-text">Watcher 命令行</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Watch-事件类型"><span class="nav-text">Watch 事件类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#watcher-使用场景"><span class="nav-text">watcher 使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ACL（Access-Control-Lists）权限控制"><span class="nav-text">ACL（Access Control Lists）权限控制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ACL-命令行"><span class="nav-text">ACL 命令行</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ACL-的构成"><span class="nav-text">ACL 的构成</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ACL-的常用使用场景"><span class="nav-text">ACL 的常用使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ACL-命令行学习"><span class="nav-text">ACL 命令行学习</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#zk-四字命令"><span class="nav-text">zk 四字命令</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Zookeeper-集群搭建"><span class="nav-text">Zookeeper 集群搭建</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xieyuanhui</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点总字数：</span>
    
    <span title="站点总字数">749k</span>
  

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    
    <span title="站点阅读时长">11:21</span>
  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.1.0</div>


<div><span id="sitetime"></span>
<script language="javascript">
  function siteTime(){
    window.setTimeout("siteTime()", 1000);
    var seconds = 1000;
    var minutes = seconds * 60;
    var hours = minutes * 60;
    var days = hours * 24;
    var years = days * 365;
    var today = new Date();
    var todayYear = today.getFullYear();
    var todayMonth = today.getMonth()+1;
    var todayDate = today.getDate();
    var todayHour = today.getHours();
    var todayMinute = today.getMinutes();
    var todaySecond = today.getSeconds();
    /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
    year - 作为date对象的年份，为4位年份值
    month - 0-11之间的整数，做为date对象的月份
    day - 1-31之间的整数，做为date对象的天数
    hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
    minutes - 0-59之间的整数，做为date对象的分钟数
    seconds - 0-59之间的整数，做为date对象的秒数
    microseconds - 0-999之间的整数，做为date对象的毫秒数 */
    var t1 = Date.UTC(2019,04,09,15,00,00); //北京时间2018-2-13 00:00:00
    var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
    var diff = t2-t1;
    var diffYears = Math.floor(diff/years);
    var diffDays = Math.floor((diff/days)-diffYears*365);
    var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
    var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
    var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
    document.getElementById("sitetime").innerHTML=" xieyuanhui的个人笔记已运行"+/*diffYears+" 年 "+*/diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
  }/*因为建站时间还没有一年，就将之注释掉了。需要的可以取消*/
  siteTime();
</script></div>



<div>

  <div class="theme-info">
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
  </div>

</div>

        






  <div>
    <script type="text/javascript">
	    var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
	    document.write(unescape("%3Cspan id='cnzz_stat_icon_1277235632'%3E%3C/span%3E%3Cscript 
	    src='" + cnzz_protocol + "s23.cnzz.com/z_stat.php%3Fid%3D1277235632%26show%3Dpic' 
	    type='text/javascript'%3E%3C/script%3E"));
    </script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  
    
    
  
  <script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="/xieyuanhui/lib/canvas-nest/canvas-nest.min.js"></script>













  
  <script src="/xieyuanhui/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/xieyuanhui/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/xieyuanhui/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="/xieyuanhui/lib/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script src="/xieyuanhui/js/utils.js?v=7.1.0"></script>

  <script src="/xieyuanhui/js/motion.js?v=7.1.0"></script>



  
  


  <script src="/xieyuanhui/js/affix.js?v=7.1.0"></script>

  <script src="/xieyuanhui/js/schemes/pisces.js?v=7.1.0"></script>



  
  <script src="/xieyuanhui/js/scrollspy.js?v=7.1.0"></script>
<script src="/xieyuanhui/js/post-details.js?v=7.1.0"></script>



  


  <script src="/xieyuanhui/js/next-boot.js?v=7.1.0"></script>


  

  

  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/xieyuanhui/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'q2BU0OM2W8i5nARddHRKQOvm-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'q2BU0OM2W8i5nARddHRKQOvm-gzGzoHsz',
                'X-LC-Key': 'hLTPk12Jmt8atnC9cePjTwQH',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
  

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$', '$'], ['\\(', '\\)'] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      
      equationNumbers: {
        autoNumber: 'AMS'
      }
    }
  });
  MathJax.Hub.Register.StartupHook('TeX Jax Ready', function() {
    MathJax.InputJax.TeX.prefilterHooks.Add(function(data) {
      if (data.display) {
        var next = data.script.nextSibling;
        while (next && next.nodeName.toLowerCase() === '#text') { next = next.nextSibling }
        if (next && next.nodeName.toLowerCase() === 'br') { next.parentNode.removeChild(next) }
      }
    });
  });
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for (i = 0; i < all.length; i += 1) {
      document.getElementById(all[i].inputID + '-Frame').parentNode.className += ' has-jax';
    }
  });
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"></script>

    
  


  

  

  

  

  
  
  
  <script src="/xieyuanhui/lib/needsharebutton/needsharebutton.js"></script>
  <script>
    
      pbOptions = {};
      
        pbOptions.iconStyle = "box";
      
        pbOptions.boxForm = "horizontal";
      
        pbOptions.position = "bottomCenter";
      
        pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
        flOptions.iconStyle = "box";
      
        flOptions.boxForm = "horizontal";
      
        flOptions.position = "middleRight";
      
        flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>


  

  

  

  

  

  


  
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({"tex2jax":{"inlineMath":[["$","$"],["\\(","\\)"]],"skipTags":["script","noscript","style","textarea","pre","code"],"processEscapes":true},"TeX":{"equationNumbers":{"autoNumber":"AMS"}}});
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->
  
</body>
</html>
